from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from . import settings
from luffyapi.utils.logger import log


def send_message(phone,code):
    try:
        client = AcsClient(settings.accessKeyId, settings.accessSecret, 'cn-hangzhou')
        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https') # https | http
        request.set_version('2017-05-25')
        request.set_action_name('SendSms')

        request.add_query_param('RegionId', "cn-hangzhou")
        request.add_query_param('PhoneNumbers', phone)
        request.add_query_param('SignName', settings.SignName)
        request.add_query_param('TemplateCode', settings.TemplateCode)
        code = {"code":code}
        request.add_query_param('TemplateParam', code)
        # "{\"code\":\"xxxx\"}"
        response = client.do_action(request)
        return response
        # python2:  print(response)
        # print(str(response, encoding = 'utf-8'))
    except Exception as e:
        log.error('手机号：%s,短信发送失败,错误为：%s' % (phone, str(e)))


# 生成一个四位随机验证码
def get_code():
    import random
    s_code=''
    for i in range(4):
        s_code+=str(random.randint(0,9))
    return '1234'

